import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:http/http.dart' as http;
import 'package:device_info_plus/device_info_plus.dart';
void main() {
  runApp(
    MaterialApp(
      home: UploadPage(),
    ),
  );
}
class FileUploader {
  // 请求存储权限
  static Future<bool> requestPermissions() async {
    if (Platform.isAndroid) {
      final androidInfo = await DeviceInfoPlugin().androidInfo;
      await Permission.manageExternalStorage.request();
      if (androidInfo.version.sdkInt >= 33) {
        // Android 13+ 需要请求音频权限
        final status = await Permission.audio.request();
        return status.isGranted;
      } else {
        // 旧版本请求存储权限
        final status = await Permission.storage.request();
        return status.isGranted;
      }
    }
    return false;
  }

  // 获取目标目录下的所有文件
  static Future<List<File>> getFiles() async {
    final externalDir = await getExternalStorageDirectory();
    final targetPath = '/storage/emulated/0/Documents/CubeCallRecorder/All/';
    //
    print(1223);
    print(targetPath);
    final targetDir = Directory(targetPath);

    if (!await targetDir.exists()) {
      print(2222);
      return [];
    };

    final List<File> files = [];
    print(targetDir.list());
    await for (var entity in targetDir.list()) {
      if (entity is File) files.add(entity);
    }
    return files;
  }

  // 上传文件到服务器
  static Future<void> uploadFiles(List<File> files, String serverUrl, String token) async {
    for (final file in files) {
      final request = http.MultipartRequest('POST', Uri.parse(serverUrl));
      request.headers['Authorization'] = 'Bearer $token';
      request.files.add(await http.MultipartFile.fromPath('file', file.path));

      try {
        final response = await request.send();
        if (response.statusCode == 200) {
          print('${file.path} 上传成功');
        } else {
          print('${file.path} 上传失败，状态码：${response.statusCode}');
        }
      } catch (e) {
        print('${file.path} 上传异常：$e');
      }
    }
  }
}

// 使用示例界面
class UploadPage extends StatefulWidget {
  @override
  _UploadPageState createState() => _UploadPageState();
}

class _UploadPageState extends State<UploadPage> {
  bool _isUploading = false;
  String _log = '';

  void _updateLog(String message) {
    setState(() => _log += '$message\n');
  }

  Future<void> _startUpload() async {
    setState(() => _isUploading = true);
    _updateLog('请求权限...');

    if (!await FileUploader.requestPermissions()) {
      _updateLog('权限被拒绝');
      setState(() => _isUploading = false);
      return;
    }

    _updateLog('获取文件中...');
    final files = await FileUploader.getFiles();
    if (files.isEmpty) {
      _updateLog('未找到文件');
      setState(() => _isUploading = false);
      return;
    }

    _updateLog('找到 ${files.length} 个文件，开始上传...');
    await FileUploader.uploadFiles(files, '你的服务器地址', '你的认证令牌');
    _updateLog('上传完成');
    setState(() => _isUploading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('文件上传')),
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          children: [
            ElevatedButton(
              onPressed: _isUploading ? null : _startUpload,
              child: Text(_isUploading ? '上传中...' : '开始上传'),
            ),
            Expanded(
              child: SingleChildScrollView(child: Text(_log)),
            ),
          ],
        ),
      ),
    );
  }
}